package net.learn2develop.GetVcb;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Xml;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity {
	static final String FEED_URL="http://www.vietcombank.com.vn/ExchangeRates/ExrateXML.aspx";
	static final String EXRATE_LIST = "ExrateList";
	static final String DATE_TIME = "DateTime";
	static final String EXRATE = "Exrate";
	private URL feedUrl;
	private List<Item> items ;
	private CustomAdapter MyAdapter;
	private String datetime;
	private ConnectivityManager connections;
	private DBAdapter db;
	ListView Mylist;
	TextView TextDateTime;
	String[] flag={"aud","cad"};
	ProgressDialog progressDialog;
	AlertDialog.Builder alert;
	String[] country_name;
	int[]  iamge_name;
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        /************Get Value*****************************/
        country_name = getResources().getStringArray(R.array.country_name);
        iamge_name = getResources().getIntArray(R.array.image_name);
        /************Progress Dialog*****************************/
        progressDialog = new ProgressDialog(this);
        progressDialog.setCancelable(false);
        progressDialog.setMessage("Loading data......");
       /*************************DBAdapter*******************/
        db = new DBAdapter(this);
        
        /*************Display Custom Adapter****************/
        alert = new AlertDialog.Builder(this);
        alert.setMessage("Network fail?")
        	 .setCancelable(false)
        	 .setPositiveButton("Open Old Datebase", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					startActivityForResult((new Intent("net.learn2develop.DETAILDB")),1);
				}
			})

			.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					dialog.dismiss();
				}
			})
			.create();
       
        
        TextDateTime = (TextView)findViewById(R.id.datetime);
       
        Mylist = (ListView)findViewById(R.id.smylist);
        items = new ArrayList<Item>();
        Item currentItem = new Item();
        currentItem.SetAtribute1("Code");
        currentItem.SetAtribute2("Buy");
        currentItem.SetAtribute3("Sell");
        items.add(currentItem);
        MyAdapter = new CustomAdapter(this, items);
        Mylist.setAdapter(MyAdapter);
        /*******************Connection State*****************/
        connections = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connections.getActiveNetworkInfo();
        if((info != null) && (info.getState() != null) ){
        	 new PaserTask().execute();
             Mylist.setOnItemClickListener(new OnItemClickListener() {

     			@Override
     			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
     					long arg3) {
     				// TODO Auto-generated method stub
     				items.clear();
     				Item currentItem = new Item();
     		        currentItem.SetAtribute1("Code");
     		        currentItem.SetAtribute2("Buy");
     		        currentItem.SetAtribute3("Sell");
     		        items.add(currentItem);
     		        new PaserTask().execute();
     			}
     		});
        }else{
        	alert.show();
        	
        }
        
        
           
    }
    /*******************************************************************/
    /****************************Result Intent*************************/
    /*******************************************************************/
   public void onActivityResult(int requestCode, int resulteCode, Intent data){
	    Toast.makeText(this, data.getData().toString(), Toast.LENGTH_LONG).show();
	    db.open();
		Item currentItem = new Item();
		Cursor c = db.getFilter("date1" + " = " + "'" + data.getData().toString()+"'", null, null, null, null);
	   	if(c.moveToFirst()){
	   		do{
	   			currentItem = new Item();
	   			currentItem.SetAtribute1(c.getString(1));
	   			currentItem.SetAtribute2(c.getString(2));
	   			currentItem.SetAtribute3(c.getString(4));
	   			
	   			TextDateTime.setText(c.getString(4));
	   			for(int i=0;i<18;i++){
						if(c.getString(1).equals(country_name[i])){
	   					currentItem.SetBitmap(BitmapFactory.decodeResource(getResources(),iamge_name[i]));
	   					break;
						}
					}
	   			items.add(currentItem);
	   			
	   		}while(c.moveToNext());
	   		
	   	}
	   	db.close();
	   	MyAdapter.notifyDataSetChanged();
	   
   }
    /*******************************************************************/
    /****************************Tast Get Paser*************************/
    /*******************************************************************/
    private class PaserTask extends AsyncTask<Void, Void, Void>{

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			parse();
			return null;
		}
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			progressDialog.show();
			super.onPreExecute();
		}
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			progressDialog.dismiss();
			if(items.isEmpty()){
				//new PaserTask().execute();
			}else{
				MyAdapter.notifyDataSetChanged();
				TextDateTime.setText(datetime);
				//items.clear();
			}
			MyAdapter.notifyDataSetChanged();
			TextDateTime.setText(datetime);
			//items.clear();
		}
    	
    }
    /*******************************************************************/
    /****************************Custom Adapter*************************/
    /*******************************************************************/
    private class CustomAdapter extends ArrayAdapter<Item>{

		public CustomAdapter(Context context, List<Item> items) {
			super(context,R.layout.list_item, items );
			// TODO Auto-generated constructor stub
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			 if (convertView == null) {
	             LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	             convertView = inflater.inflate(R.layout.list_item, parent, false);
	          }
			 TextView text1 = (TextView)convertView.findViewById(R.id.text1);
			 TextView text2 = (TextView)convertView.findViewById(R.id.text2);
			 TextView text3 = (TextView)convertView.findViewById(R.id.text3);
			 ImageView image= (ImageView)convertView.findViewById(R.id.image);
			 Item item = getItem(position);
			 if(item!=null){
				 text1.setText(item.GetAtribute1());
				 text2.setText(item.GetAtribute2());
				 text3.setText(item.GetAtribute3());
				 image.setImageBitmap(item.GetBitmap());
			 }
			return convertView;
		}
    	
    }
    /*******************************************************************/
    /******************************Parse Xml****************************/
    /*******************************************************************/
    public void parse(){
    	Item currenttemItem = null;
      	XmlPullParser ParseXml = Xml.newPullParser(); // Tao ra 1 XmlPullParser
        Cursor c;
    	try {
			feedUrl = new URL(FEED_URL);
			ParseXml.setInput(feedUrl.openConnection().getInputStream(), null);//set Input, tao ket noi
	    	int eventType = ParseXml.getEventType();
	    	while(eventType != XmlPullParser.END_DOCUMENT){
	    		String name = null;
	    		switch(eventType){
	    		case XmlPullParser.START_DOCUMENT:
	    			currenttemItem = new Item();
	    			db.open();
	    		 	break;
	    		case XmlPullParser.START_TAG:
	    			name = ParseXml.getName();
	    			
	    			if(name.equalsIgnoreCase(EXRATE_LIST)){
	    				//Toast.makeText(getBaseContext(), ParseXml.nextText(), Toast.LENGTH_LONG).show();
	    			}else if(name.equalsIgnoreCase(DATE_TIME)){
	    				datetime = ParseXml.nextText();
	    					    				
	    			}else if(name.equalsIgnoreCase(EXRATE)){
	    				currenttemItem = new Item();
	    				currenttemItem.SetAtribute1(ParseXml.getAttributeValue(0));
	    				currenttemItem.SetAtribute2(ParseXml.getAttributeValue(2));
	    				currenttemItem.SetAtribute3(ParseXml.getAttributeValue(4));
	    				db.insertContact(ParseXml.getAttributeValue(0)
	    						,ParseXml.getAttributeValue(2), ParseXml.getAttributeValue(4),datetime,"0");
	    				for(int i=0;i<18;i++){
	    					if(ParseXml.getAttributeValue(0).equals(country_name[i])){
		    					currenttemItem.SetBitmap(BitmapFactory.decodeResource(getResources(), iamge_name[i]));
		    					break;
	    					}
	    				}
	    				items.add(currenttemItem);
	    				
	    			}
	    		case XmlPullParser.END_TAG:
	    			name = ParseXml.getName();
	    			
	    			if(name != null){
	    				if(name.equalsIgnoreCase("Source")){
	    					//items.clear();
	    					currenttemItem = null;
	    					//items.clear();
	    					    					
	    				}
	    			}
	    			
	    			break;
	    		case XmlPullParser.END_DOCUMENT:
	    			break;
	    		}
	    	/*	c = db.getAllContacts();
	    		if(c.moveToFirst()){
	    			do{
	    				if(datetime.equals(c.getString(4)))
	    					break;
	    			}while(c.moveToNext());
	    		}
	    		if(c.moveToNext()) break;*/
	    		eventType = ParseXml.next();
	    	}
	    	db.close();
	    	
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
		
			//e.printStackTrace();
			
			// TODO Auto-generated catch block
		} catch (XmlPullParserException e) {
			
			// TODO Auto-generated catch block
		
			// TODO Auto-generated catch block
			//e.printStackTrace();
		} catch (IOException e) {
			// alert.show();
			//e.printStackTrace();
		}
    	
    	
    	
    }
   
}